package com.wuyan.web.form.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyan.web.base.aop.ApiLogAnnotation;
import com.wuyan.web.base.helper.BaseApi;
import com.wuyan.web.base.helper.mongo.MongodbHelper;
import com.wuyan.web.base.helper.rep.RepBody;
import com.wuyan.web.base.helper.rep.RepHelper;
import com.wuyan.web.base.helper.req.CustomGroupParams;
import com.wuyan.web.base.helper.req.CustomQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/count")
public class CountApi extends BaseApi implements RepHelper {

    @Autowired
    private MongodbHelper mongodbHelper;

    @Autowired
    private ObjectMapper mapper;

    /**
     * 分组排序功能
     *
     * @param table       集合名称
     * @param unwind      数组拆分标识
     * @param fieldNames  分组字段名
     * @param groupParams 分组参数
     * @param params      查询条件
     * @return RepBody<List < Map>>
     * @throws JsonProcessingException e
     */
    @GetMapping("/{table}")
    @ApiLogAnnotation(name = "Count:count")
    public RepBody<List<Map>> count(@PathVariable("table") String table,
                                    @RequestParam(value = "unwind", required = false, defaultValue = "") String unwind,
                                    @RequestParam(value = "fieldNames", required = false, defaultValue = "[]") String fieldNames,
                                    @RequestParam(value = "groups", required = false, defaultValue = "[]") String groupParams,
                                    @RequestParam(value = "params", required = false, defaultValue = "[]") String params)
            throws JsonProcessingException {
        // 排序参数
        String[] fieldNamesList = mapper.readValue(fieldNames, new TypeReference<String[]>() {
        });
        // 查询参数
        List<CustomQueryParams> paramsList = mapper.readValue(params, new TypeReference<List<CustomQueryParams>>() {
        });
        // 排序参数
        List<CustomGroupParams> groupList = mapper.readValue(groupParams, new TypeReference<List<CustomGroupParams>>() {
        });
        List<Map> list = mongodbHelper.countByGroup(table, Map.class, unwind, fieldNamesList, groupList, paramsList);
        return ok(list);
    }
}
